package com.android.fragmentdemo.thread4

import org.junit.Test

class Demo4 {
    @Test
    fun testRunnable() {

        val runnable = TicketSale()

        val th1 = Thread(runnable,"A")
        val th2 = Thread(runnable,"B")
        val th3 = Thread(runnable,"C")
        val th4 = Thread(runnable,"D")
        val th5 = Thread(runnable,"E")
        val th6 = Thread(runnable,"F")
        val th7 = Thread(runnable,"G")
        val th8 = Thread(runnable,"H")

        th1.start()
        th2.start()
        th3.start()
        th4.start()
        th5.start()
        th6.start()
        th7.start()
        th8.start()

        Thread.sleep(10 * 1000)
    }

    class TicketSale : Runnable {
        private var ticket = 5
        override fun run() {
            for (i in 0..200) {
                try {
                    Thread.sleep(200)
                } catch (ex: InterruptedException) {
                    ex.printStackTrace()
                }
                this.sale()
            }
        }

        @Synchronized
        private fun sale() {
            if (ticket > 0) {
                println("${Thread.currentThread().name},正在售出第${ticket--}张票")
            }
        }
    }
}